package com.boot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;


@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //接口路径授权配置
        http.authorizeHttpRequests(authorizeHttpRequests ->
                authorizeHttpRequests
                        //********************************角色****************************************
                        //.requestMatchers("/admin/api").hasRole("admin") //必须有admin角色才能访问到
                        //.requestMatchers("/user/api").hasAnyRole("admin","user") // /user/api:admin、user都是可以访问

                        //********************************权限****************************************
                        .requestMatchers("/admin/api").hasAuthority("admin:api") //必须有admin:api权限才能访问到
                        .requestMatchers("/user/api").hasAnyAuthority("admin:api", "user:api") //有admin:api、user:api权限能访问到


                        //********************************匹配模式****************************************
                        .requestMatchers("/admin/api/?").hasAuthority("admin:api") //必须有admin:api权限才能访问到
                        .requestMatchers("/user/api/my/*").hasAuthority("admin:api") //必须有admin:api权限才能访问到

                        .requestMatchers("/admin/api/a/b/**").hasAuthority("admin:api") //必须有admin:api权限才能访问到

                        .requestMatchers("/app/api").permitAll() //允许任何人访问

                        .requestMatchers("/login").permitAll()
                        .anyRequest().authenticated()
        );
        //借助异常处理配置一个未授权页面
        http.exceptionHandling(e -> e.accessDeniedPage("/noAuth"));

        //登录
        http.formLogin(formLogin ->
                formLogin
                        .loginPage("/login")
                        .loginProcessingUrl("/login")
                        .defaultSuccessUrl("/index")

        );


        //关闭
        http.csrf(AbstractHttpConfigurer::disable);

        //退出
        http.logout(logout -> logout.invalidateHttpSession(true));

        return http.build();
    }

    /**
     * PasswordEncoder:加密编码
     * 实际开发中开发环境一般是明文加密 在生产环境中是密文加密 也就可以可以配置多种加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        //明文加密
        return NoOpPasswordEncoder.getInstance();
    }

}
